package com.htwy.core.realms;

import com.htwy.core.model.Account;
import com.jfinal.kit.HashKit;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class ShiroDbRealm extends AuthorizingRealm {

    public String getName() {
        return "ShiroDbRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        SimpleAuthenticationInfo authenticationInfo = null;

        Account account = Account.dao.findByUsername(username);

        if (account == null) {
            throw new UnknownAccountException();
        }

        if (!account.getPassword().equals(HashKit.md5(account.getAccount() + account.getSalt() + upToken.getPassword()))) {
            throw new IncorrectCredentialsException();
        }

        authenticationInfo = new SimpleAuthenticationInfo(account, account.getPassword(), ByteSource.Util.bytes(account.getSalt()), getName());

        return authenticationInfo;
    }

}
